###########################################################################
#	$Id: MyCache.p 35 2008-07-20 23:27:09Z beave $
###########################################################################

@CLASS
MyCache

@USE
bLib.p
CachePage.p


@auto[]
$self.REQUEST_URI[$request:uri]
$self.QUERY[$request:query]

# setting default cache time to 1 hour
$self.TIME(3600)

$self.CACHE_FILE[/../data/_cache.cfg]
$self.CACHE_PATH[/../data/cache]
#end @auto[]



@init[hshParams][hParams;tCache]
$hParams[^hash::create[$hshParams]]

^if(def $hParams.REQUEST_URI){
	$REQUEST_URI[$hParams.REQUEST_URI]
}

^if(def $hParams.QUERY){
	$QUERY[$hParams.QUERY]
}

^if(def $hParams.CACHE_FILE){
	$CACHE_FILE[^bLib:preparePath[$hParams.CACHE_FILE]]
}

^if(def $hParams.CACHE_PATH){
	$CACHE_PATH[^bLib:preparePath[$hParams.CACHE_PATH]]
}

^if(-f $CACHE_FILE){
#	loading site's paths with cache time
	$tCache[^table::load[/../data/_cache.cfg]]
	
#	determining cache time to this URI
	^if(^tCache.locate[path;$REQUEST_URI]){
		$TIME(^tCache.time.int($self.TIME))
	}
}
#end @init[]



@run[jnBody][tRepl;tURIParts;sFileName;oCachePage]
^if($env:REQUEST_METHOD eq "POST"){
	$result[$jnBody]
}{
	$tRepl[^table::create[nameless]{?	&&}]
	
#	cleaning query
	$QUERY[^QUERY.replace[$tRepl]]
	$QUERY[^QUERY.match[&{2,}][g]{}]
	
#	splitting URI to get filename
	$tURIParts[^REQUEST_URI.split[?][hl]]
	$sFileName[^if($tURIParts.0 eq "/"){_main}{$tURIParts.0}]
	
	
#	specifying the cache key
	$self.KEY[$sFileName^if(def $QUERY){^math:md5[$QUERY]}]
	
	
	$oCachePage[^CachePage::create[
		$.sCacheDir[$CACHE_PATH]
	]]
	
	^oCachePage.run[$KEY]($TIME){$jnBody}
}
#end @run[]
